import {
  View,
  Text,
  TouchableOpacity,
  Dimensions,
  Image,
  ActivityIndicator,
  Platform,
} from 'react-native';
import {
  primaryBackgroundColor,
  primaryColor,
  primaryColor2,
  primaryBackgroundColor3,
  secondaryColor,
  secondaryBorderColor,
} from '../../../../theme/default';
import React, {useEffect, useState} from 'react';

import {NativeStackNavigationProp} from '@react-navigation/native-stack';

import CardIcon from '../../../../assets/icons/card.svg';
import {IdentityModel} from '../../../../db/models/identityModel';
import {useRegister} from '../../../../hooks/useRegister';
import {useIdentityProvider} from '../../../../hooks/useSIWPIdentity';
import {generatePasskeyTitle} from '../../../../utils';
import type {RootStackParamList} from '../../../Nav/routes';
import {UpNetworkLogo} from '../../../UI/UpNetworkLogo';
import {useTranslation} from 'react-i18next';
import {UserModel} from '../../../../db/models/userModel';
import Toast from 'react-native-toast-message';
import LoadingModal from '../../../UI/Common/LoadingModal';
import SimpleModal2 from '../../../UI/Common/SimpleModal2';

type LoginScreenNavigationProp = NativeStackNavigationProp<
  RootStackParamList,
  'Login'
>;

type Props = {
  navigation: LoginScreenNavigationProp;
};

const {width} = Dimensions.get('window');

function LoginView({navigation}: Readonly<Props>) {
  const {t} = useTranslation();
  const {loginStatus, login, loginError} = useIdentityProvider();
  const {registerFast, error} = useRegister();
  const [loading, setLoading] = useState<boolean>();
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);

  useEffect(() => {
    if (loginError != undefined) {
      console.log('loginError = ', loginError);
      Toast.show({
        type: 'error',
        text1: t('loginTitle'),
        text2: loginError.message,
        position: Platform.OS === 'android' ? 'top' : 'bottom',
      });
    }
  }, [loginError]);

  useEffect(() => {
    if (error != '') {
      Toast.show({
        type: 'error',
        text1: t('registerFastTitle'),
        text2: error,
        position: Platform.OS === 'android' ? 'top' : 'bottom',
      });
    }
  }, [error]);

  const handleSignUpAnonymously = async () => {
    try {
      setLoading(true);
      const response = await registerFast({
        passkeyTitle: generatePasskeyTitle(),
      });

      if (response == undefined) {
        setLoading(false);
        return;
      }

      await login(response);
    } catch (error) {}
  };

  useEffect(() => {
    if (loginStatus != 'logging-in') {
      setLoading(false);
    }
  }, [loginStatus]);

  const handleLogin = async () => {
    try {
      if (loginStatus == 'logging-in') {
        return;
      }

      const im = new IdentityModel();
      const identity = await im.getSelected();
      if (identity != null) {
        setLoading(true);
        await login(identity.uid);
      } else {
        const userModel = new UserModel();
        const userList = await userModel.getAll();

        if (userList.length == 0) {
          setIsModalVisible(true);
        } else {
          setLoading(true);
          await login();
        }
      }
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <View
      style={{
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: primaryBackgroundColor,
      }}>
      <View style={{marginBottom: 32}}>
        <UpNetworkLogo width={150} />
      </View>
      <View style={{marginBottom: 64}}>
        <Image
          source={require('../../../../assets/images/wallet.png')}
          style={{width: 200, height: 200}}
        />
      </View>

      <View
        style={{
          marginBottom: 24,
          justifyContent: 'center',
          alignItems: 'center',
        }}>
        <Text style={{fontSize: 15, fontWeight: '600', color: secondaryColor}}>
          {t('registerWith')}
        </Text>
      </View>

      <View
        style={{
          justifyContent: 'center',
          alignItems: 'center',
          marginBottom: 32,
        }}>
        <TouchableOpacity
          onPress={() => {
            navigation.push('Register');
          }}
          style={{
            backgroundColor: primaryBackgroundColor3,
            padding: 8,
            borderRadius: 64,
          }}>
          <CardIcon width={30} height={30} color={primaryColor} />
        </TouchableOpacity>
      </View>

      <TouchableOpacity
        onPress={async () => {
          handleLogin();
        }}
        style={{
          width: width - 64,
          padding: 12,
          justifyContent: 'center',
          alignItems: 'center',
          borderRadius: 16,
          borderWidth: 2,
          borderColor: primaryColor,
          marginBottom: 12,
        }}>
        <View
          style={{
            justifyContent: 'center',
            alignItems: 'center',
            flexDirection: 'row',
          }}>
          {/* {loginStatus == 'logging-in' && (
            <ActivityIndicator
              size="small"
              color={primaryColor}
              style={{marginRight: 6}}
            />
          )} */}
          <Text style={{color: primaryColor2, fontSize: 16, fontWeight: '600'}}>
            {t('loginButtonTitle')}
          </Text>
        </View>
      </TouchableOpacity>

      <TouchableOpacity
        onPress={() => {
          handleSignUpAnonymously();
        }}
        style={{
          width: width - 64,
          padding: 12,
          justifyContent: 'center',
          alignItems: 'center',
          borderRadius: 16,
          borderWidth: 2,
          borderColor: secondaryBorderColor,
          marginBottom: 24,
        }}>
        <Text style={{color: secondaryColor, fontSize: 16, fontWeight: '600'}}>
          {t('signUpButtonTitle')}
        </Text>
      </TouchableOpacity>

      <TouchableOpacity
        onPress={() => {
          navigation.navigate('Terms');
        }}
        style={{
          width: width - 64,
          justifyContent: 'center',
          flexDirection: 'row',
        }}>
        <Text style={{color: primaryColor2}}>{t('termsHint')}</Text>
        <Text style={{color: primaryColor}}>{t('terms')}</Text>
      </TouchableOpacity>
      <LoadingModal
        visible={loading == undefined ? false : loading}></LoadingModal>
      {isModalVisible && (
        <SimpleModal2
          leftButtonTitle={t('signUpWithPasskey')}
          rightButtonTitle={t('loginTitle')}
          visible={isModalVisible}
          onClose={() => {
            setIsModalVisible(!isModalVisible);
          }}
          title={t('loginButtonTitle')}
          content={t('loginHint')}
          onLeftConfirm={() => {
            setIsModalVisible(false);
            setTimeout(() => {
              handleSignUpAnonymously();
            }, 500);
          }}
          onRightConfirm={() => {
            setIsModalVisible(false);
            setTimeout(async () => {
              setLoading(true);
              await login();
            }, 500);
          }}></SimpleModal2>
      )}
    </View>
  );
}

export default LoginView;
